package cn.com.dingtek.genius.manager.server.service;

import cn.com.dingtek.genius.manager.server.repository.db.entity.UserBase;
import cn.com.dingtek.genius.manager.server.repository.db.manager.UserBaseManager;
import cn.com.dingtek.genius.manager.server.utils.Verify;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.nio.charset.StandardCharsets;

@Service
public class ProfileService {
    @Autowired
    private UserBaseManager userBaseManager;

    public long verifyLogin(String account, String passwd) {
        Verify.isTrue(StringUtils.isNotBlank(account), "请输入正确登录账号");
        Verify.isTrue(StringUtils.isNotBlank(passwd), "请输入正确密码");

        UserBase userBase = userBaseManager.getOne(new QueryWrapper<UserBase>().eq("account_name", account));
        Verify.notNull(userBase, "请输入正确登录账号");

        String passwdHash = DigestUtils.md5DigestAsHex(passwd.getBytes(StandardCharsets.UTF_8));
        Verify.isTrue(passwdHash.equals(userBase.getPasswd()), "请输入正确密码");

        return userBase.getId();
    }

    public UserBase info(long userId) {
        UserBase userBase = userBaseManager.getById(userId);
        Verify.notNull(userBase, "用户不存在");
        return userBase;
    }

    public void repasswd(long userId, String oldPasswd, String newpasswd) {
        Verify.isTrue(StringUtils.isNotBlank(oldPasswd), "请输入正确密码");
        Verify.isTrue(StringUtils.isNotBlank(newpasswd), "请输入正确密码");

        UserBase userBase = userBaseManager.getById(userId);

        String passwdHash = DigestUtils.md5DigestAsHex(oldPasswd.getBytes(StandardCharsets.UTF_8));
        Verify.isTrue(passwdHash.equals(userBase.getPasswd()), "请输入正确密码");
        String passwdHash_new = DigestUtils.md5DigestAsHex(newpasswd.getBytes(StandardCharsets.UTF_8));

        userBaseManager.updateById(UserBase.builder().id(userId).passwd(passwdHash_new).build());
    }
}
